﻿//#define ErpNotReady
using DadayunApi.Model;
using KbtSync.DAL;
using KbtSync.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace KbtSync.BLL
{
    public class DdySyncBLL
    {
        SunlikeDAL erpDAL;
        DadayunDAL ddyDAL;
        public string ResponseJson { get { return ddyDAL.ResponseJosn; } }
        public string WritingJson { get{ return ddyDAL.WritingJson; } }
        public HttpStatusCode httpStatusCode;
        public DdySyncBLL(string sunlikeConnstr, string ddyBaseUri, AppAuthBase ddyAuthBase)
        {
            erpDAL = new SunlikeDAL(sunlikeConnstr);
            ddyDAL = new DadayunDAL(ddyAuthBase,ddyBaseUri);
        }
        public  int StorageSync1x1Mode()
        {
            int count = 0;//用于返回更新的产品条数
            //获取CRM所有的仓库清单
            List<IdName> crmWarehouses = ddyDAL.GetProductWarehouses();
            //读取CRM中产品清单
            IList<ProductReportResult> crmProducts = ddyDAL.GetProductList();
            if (crmProducts.Count < 0) return count;
            List<StorageResult> crmStorages = ddyDAL.GetStorageReports();
            //更新每个产品的库存信息
            List<StorageForm> storageForms = new List<StorageForm>();
            StorageForm storageForm = null;

            #region 循环查询产品清单
            ProductReportResult p = crmProducts[0];
            StorageResult crmStoage = crmStorages.FirstOrDefault(s => s.ErpItemCode == p.ErpItemCode);
            if (crmStoage == null)
            {//无库存信息
                List<Storage> storages = new List<Storage>();
                foreach (var w in crmWarehouses)
                {
                    double erpQty = 100;//正常使用时用以下代替
                    //double erpQty = erpDAL.GetStorageQty(p.ErpItemCode, w.Name);
                                  
                    storages.Add(new Storage
                    {
                        //Id = Guid.NewGuid().ToString(),
                        //Action = EActions.Create.ToString(),
                        Warehouse = w.Name,
                        StoreQty = erpQty,
                        UsableQty = erpQty,
                        Note = "调试程序用"
                    });
                }
                storageForm = new StorageForm
                {
                    //Id = string.Empty,//新建时,ID为空值
                    //Action= EActions.Create.ToString(),
                    ErpItemCode = p.ErpItemCode,
                    ProdName = p.ProdName,
                    Storages = storages
                };
                if (ddyDAL.CreateStorageForm(storageForm) == HttpStatusCode.Created)
                {
                    count++;
                }
            }
            else
            {
                List<Storage> storages = new List<Storage>();
                foreach (var w in crmWarehouses)
                {
                    double erpQty = 100;//正常使用时替换成以仓名,产品代码从ERP中查出
                    StorageResult crmStorage = crmStorages.FirstOrDefault(s => s.ErpItemCode == p.ErpItemCode && s.WareHouse == w.Name);
                    if (crmStorage == null)
                    {
                        storages.Add(new Storage
                        {
                            //Id=Guid.NewGuid().ToString(),
                            //Action = EActions.Create.ToString(),
                            Warehouse = w.Name,
                            StoreQty = erpQty,
                            UsableQty = erpQty,
                            Note = "调试程序,正常使用时数量应以仓名,产品代码从ERP中查出"
                        });
                    }
                    else if (crmStorage.StockQty != erpQty)
                    {
                        storages.Add(new Storage
                        {
                            Id = crmStorage.DataObjs.FormInstances[0].SubFormInstances[0].InstanceId,
                            //Action =EActions.Update.ToString(),
                            Warehouse = w.Name,
                            StoreQty = erpQty,
                            UsableQty = erpQty,
                            Note = "调试程序,正常使用时数量应以仓名,产品代码从ERP中查出"
                        });
                    }
                    if (storages.Count > 0)
                    {
                        storageForm = ddyDAL.GetStorageForm(crmStorage.DataObjs.FormInstances[0].InstanceId);
                        storageForm.Storages = storages;
                    }
                    if(ddyDAL.EditStorageForm(storageForm.Id,storageForm)==HttpStatusCode.OK)
                    {
                        count++;
                    }
                }
            }
            if (storageForm != null)
                storageForms.Add(storageForm);
            #endregion
            
            return count;
        }

        public IList<ProductReportResult> GetProductList()
        {
            return ddyDAL.GetProductList();
        }
        public IList<ProductReportResult> GetProductList(int start, int count, out int totalCount)
        {
            return ddyDAL.GetProductList(start, count,out totalCount);
        }
        /// <summary>
        /// 批量写入模式更新库存, 可调整数量大小
        /// </summary>
        /// <param name="errCount">出错的数量</param>
        /// <returns>实际更新数量</returns>
        public int  StorageSyncBatchMode(IEnumerable<ProductReportResult> products, int  pageSize, out int errCount)
        {
            errCount = 0;
            int susCount = 0;
            int counting = 0;
            bool modified = false;
            if (products.Count() <= 0) return 0;
            //获取CRM所有的仓库清单
            List<IdName> crmWarehouses = ddyDAL.GetProductWarehouses();
            
            List<StorageForm> storageForms = new List<StorageForm>();
            foreach (ProductReportResult p in products)
            {
                counting++;
                //更新每个产品的库存信息                
                StorageForm storageForm = null;                
                List<StorageResult> crmStorageRes = ddyDAL.GetStorageReports(p.ErpItemCode, p.Version);
                if (crmStorageRes == null)
                {//无库存信息,则新增库存信息表,并在ERP中查找库存信息
                    List<Storage> storages = new List<Storage>();
                    foreach (var w in crmWarehouses)
                    {
#if ErpNotReady
                        double erpQty = 100;//正常使用时用以下代替                        
#else
                        double erpQty = erpDAL.GetStorageQty(p.ErpItemCode, w.Name, p.Version);
                        //string note = "";
#endif
                        storages.Add(new Storage
                        {
                            //Id = Guid.NewGuid().ToString(),
                            //Action = EActions.Create.ToString(),
                            Warehouse = w.Name,
                            StoreQty = erpQty,
                            Note = "新增产品"
                        });
                    }
                    storageForm = new StorageForm
                    {
                        //Id = string.Empty,//新建时,ID为空值
                        //Action= EActions.Create.ToString(),
                        ErpItemCode = p.ErpItemCode,
                        ProdName = p.ProdName,
                        Version = p.Version,
                        Storages = storages
                    };
                    modified = true;
                }
                else//有库存信息,则找到库存信息表,并修改库存信息表的的库存数据
                {
                    //找到库存信息表实例
                    string instanceId = crmStorageRes[0].DataObjs.FormInstances[0].InstanceId;
                    storageForm = ddyDAL.GetStorageForm(instanceId);
                    //List<Storage> storages = new List<Storage>();
                    foreach (var w in crmWarehouses)
                    {
#if ErpNotReady
                        double erpQty = 200;//正常使用时替换成以仓名,产品代码从ERP中查出                       
#else
                        double erpQty = erpDAL.GetStorageQty(p.ErpItemCode, w.Name, p.Version);
                        //string note = "";
#endif
                        //List<StorageResult> crmStorages = ddyDAL.GetStorageReports(p.ErpItemCode, p.Version);
                        StorageResult crmStg = crmStorageRes.FirstOrDefault(s => s.ErpItemCode == p.ErpItemCode&&s.Version==p.Version && s.WareHouse == w.Name);

                        if (crmStg == null)
                        {
                            storageForm.Storages.Add(new Storage
                            {
                                //Id=Guid.NewGuid().ToString(),
                                //Action = EActions.Create.ToString(),
                                Warehouse = w.Name,
                                StoreQty = erpQty,
                                LockQty=0,
                                UsableQty=erpQty,
                                Note = "新增库存"
                            });
                            modified = true;
                        }
                        else if (crmStg.StockQty != erpQty)
                        {
                            //找到库存子表项
                            string Id = crmStg.DataObjs.FormInstances[0].SubFormInstances[0].InstanceId;//库存子表ID
                            int index = storageForm.Storages.FindIndex(s => s.Id == Id);//库存子表索引
                            storageForm.Storages[index].StoreQty = erpQty;  //修改库存数量    
                            storageForm.Storages[index].Note = "修改库存数量";
                            storageForm.Storages[index].UsableQty = storageForm.Storages[index].StoreQty - storageForm.Storages[index].LockQty;
                            modified = true;
                        }
                    }
                    
                }
                if (modified)
                    storageForms.Add(storageForm);
                if (storageForms.Count == pageSize || counting>=products.Count())
                {//如果表单数量已经达到既定数量或者已经查询完,就更新库存
                    susCount += SyncingStorage(storageForms, out int eCount);
                    errCount += eCount;
                    storageForms.Clear();
                }

            }
            
            
            return susCount;
        }

        private int SyncingStorage(List<StorageForm> storageForms, out int errCount)
        {
            errCount = 0;
            int susCount = 0;
            if (storageForms.Count <= 0) return 0;
            httpStatusCode = ddyDAL.BatchProceed(storageForms, out int count);            
            if (httpStatusCode == HttpStatusCode.OK)
            {
                susCount = count;
            }            
            else
            {
                errCount += storageForms.Count;
            }
            return susCount;
        }

        /// <summary>
        /// 批量写入模式更新库存, 数量8399时失败
        /// </summary>
        /// <returns></returns>
        public HttpStatusCode StorageSyncBatchMode( out int count)
        {
            count = 0;
            //获取CRM所有的仓库清单
            List<IdName> crmWarehouses = ddyDAL.GetProductWarehouses();
            //读取CRM中产品清单
            IList<ProductReportResult> crmProducts = ddyDAL.GetProductList();
            if (crmProducts.Count < 0) return HttpStatusCode.NotFound;
            //获取CRM的库存报表
            List<StorageResult> crmStorages = ddyDAL.GetStorageReports();
            //更新每个产品的库存信息
            List<StorageForm> storageForms = new List<StorageForm>();
            StorageForm storageForm = null;

            #region 循环查询产品清单
            foreach (var p  in crmProducts)
            {
                StorageResult crmStoage = null;
                if (crmStorages != null)
                    crmStoage = crmStorages.FirstOrDefault(s => s.ErpItemCode == p.ErpItemCode&&s.Version==p.Version);
                if (crmStoage == null)
                {//无库存信息,则新增库存信息表,并在ERP中查找库存信息
                    List<Storage> storages = new List<Storage>();
                    foreach (var w in crmWarehouses)
                    {
#if ErpNotReady
                        double erpQty = 100;//正常使用时用以下代替
                        string note = "调试程序用";
#else
                        double erpQty = erpDAL.GetStorageQty(p.ErpItemCode, w.Name, p.Version);
                        string note="";
#endif
                        storages.Add(new Storage
                        {
                            //Id = Guid.NewGuid().ToString(),
                            //Action = EActions.Create.ToString(),
                            Warehouse = w.Name,
                            StoreQty = erpQty,
                            Note = note
                        });
                    }
                    storageForm = new StorageForm
                    {
                        //Id = string.Empty,//新建时,ID为空值
                        //Action= EActions.Create.ToString(),
                        ErpItemCode = p.ErpItemCode,
                        ProdName = p.ProdName,
                        Version=p.Version,
                        Storages = storages
                    };
                }
                else//有库存信息,则找到库存信息表,并修改库存信息表的的库存数据
                {
                    //找到库存信息表实例
                    string instanceId = crmStoage.DataObjs.FormInstances[0].InstanceId;
                    storageForm = ddyDAL.GetStorageForm(instanceId);
                    List<Storage> storages = new List<Storage>();
                    foreach (var w in crmWarehouses)
                    {
#if ErpNotReady
                        double erpQty = 200;//正常使用时替换成以仓名,产品代码从ERP中查出
                        string note = "调试程序用";
#else
                        double  erpQty = erpDAL.GetStorageQty(p.ErpItemCode, w.Name,p.Version);
                        string note = "调试程序用";
#endif
                        StorageResult crmStorage = crmStorages.FirstOrDefault(s => s.ErpItemCode == p.ErpItemCode && s.WareHouse == w.Name);
                        if (crmStorage == null)
                        {
                            storageForm.Storages.Add(new Storage
                            {
                                //Id=Guid.NewGuid().ToString(),
                                //Action = EActions.Create.ToString(),
                                Warehouse = w.Name,
                                StoreQty = erpQty,
                                Note = note
                            });
                        }
                        else if (crmStorage.StockQty != erpQty)
                        {
                            //找到库存子表项
                            string Id = crmStorage.DataObjs.FormInstances[0].SubFormInstances[0].InstanceId;//库存子表ID
                            int index = storageForm.Storages.FindIndex(s => s.Id == Id);//库存子表索引
                            storageForm.Storages[index].StoreQty = erpQty;  //修改库存数量                         
                        }
                    }
                    if (storages.Count > 0)
                    {
                        storageForm.Storages = storages;
                    }
                }
                if (storageForm != null)
                    storageForms.Add(storageForm);
            }
            
#endregion
            var ans = ddyDAL.BatchProceed(storageForms,out count);
            return ans;
        }
        public bool IsErpReady()
        {
            return erpDAL.DbReady();
        }
        public bool IsDdyReady()
        {
            return ddyDAL.GetServerTime() > DateTime.MinValue;
        }
        private bool ClearStorageInfo(string erpItemCode)
        {
            return ddyDAL.ClearStorageInfo(erpItemCode);
        }

        private bool ExistStorageInfo(string erpItemCode)
        {
            List< StorageResult >  ans= ddyDAL.GetStorageReports(erpItemCode);
            return ans.Count > 0;
        }

    }
}
